﻿/*************************************************************************
 * Created by OhZee Creative, LLC
 * 2013
 * This code is licensed under Microsoft Public License (Ms-PL)
 * http://opensource.org/licenses/ms-pl
 * http://ozframework.codeplex.com/
 *************************************************************************/

namespace OhZeeCreative.Sound.Windows8
{
    using System;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Media;

    public class SoundChannel
	{
		public SoundChannel()
		{
			this.MediaElement = new MediaElement()
			{
				AutoPlay = false,
				Visibility = Visibility.Collapsed,
				AudioDeviceType = AudioDeviceType.Multimedia,
				AudioCategory = AudioCategory.GameEffects,
			};

			this.MediaElement.MediaOpened += MediaElement_MediaOpened;
		}

		void MediaElement_MediaOpened(object sender, RoutedEventArgs e)
		{
			MediaElement me = (MediaElement)sender;

			if (!me.AutoPlay)
			{
				me.Play();
			}
		}

		public MediaElement MediaElement { get; private set; }
		public bool IsBusy
		{
			get
			{
				return this.MediaElement.CurrentState != MediaElementState.Closed &&
					   this.MediaElement.CurrentState != MediaElementState.Stopped &&
					   this.MediaElement.CurrentState != MediaElementState.Paused;
			}
		}
		public DateTime StartTime { get; private set; }
		public SoundRequest SoundRequest { get; private set; }

		public void Play(SoundRequest request)
		{
			if (!this.IsBusy)
			{
				this.MediaElement.AutoPlay = request.PlayMode == SoundPlayMode.Immediate;
				this.MediaElement.Source = request.SoundItem.FileUri;
				this.StartTime = DateTime.Now;
			}
		}

		public void Stop()
		{
			this.MediaElement.Stop();
		}

		public void Reset()
		{
			this.MediaElement.Stop();
			this.MediaElement.Source = null;
			this.StartTime = DateTime.MinValue;
		}
	}
}